package frontend.pages.admin.team;

import backend.model.admin.Team;
import backend.model.other.User;
import shared.other.UserRolesDefinition;
import backend.service.admin.TeamService;
import backend.service.other.UserService;
import frontend.core.TimeTrackingWebApplication;
import frontend.core.TimeTrackingWebSession;
import frontend.model.admin.TeamUIModel;
import frontend.pages.admin.base.AbstractManagingPage;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.markup.html.panel.Panel;
import org.wicketstuff.annotation.mount.MountPath;

import java.util.LinkedList;
import java.util.List;

import static shared.other.UserRolesDefinition.ADMIN_ROLE_KEY;
import static shared.other.UserRolesDefinition.FOREMAN_ROLE_KEY;

@MountPath("team")
@AuthorizeInstantiation(value = {FOREMAN_ROLE_KEY, ADMIN_ROLE_KEY})
public class TeamManagingPage extends AbstractManagingPage<Team> {

    private static final int DEFAULT_TEAM_ID = 1;

	public TeamManagingPage() {
		super("pages.admin.team.title", "contextualHelp.admin.team.text");
	}

    @Override
    protected String getAddPanelTitleKey() {
        return "pages.admin.team.add.title";
    }

    @Override
    protected String getEditPanelTitleKey() {
        return "pages.admin.team.edit.title";
    }

    @Override
    protected String getNoSelectionMessageKey() {
        return "pages.admin.team.edit.noSelection";
    }

    @Override
    protected Panel getAddPanel(String panelId) {
        return new TeamPanel(panelId, getPageParameters(), new TeamUIModel());
    }

    @Override
    protected Panel getEditPanel(String panelId, Team team) {
        getPageParameters().clearNamed();
        return new TeamPanel(panelId, null, new TeamUIModel(team));
    }

    @Override
    public List<Team> loadAvailableEntities() {
        TeamService teamService = TimeTrackingWebApplication.getService(TeamService.class);

        String loggedInUsername = (String) TimeTrackingWebSession.get().getAttribute(TimeTrackingWebSession.LOGIN_USERNAME_ATTR);
        User user = TimeTrackingWebApplication.getService(UserService.class).findUserByUsername(loggedInUsername);
        boolean isForeman = UserRolesDefinition.UserRole.FOREMAN.equals(user.getRole());

        List<Team> allTeams;
        if (isForeman) {
           allTeams = teamService.findAllActiveTeamsOfForeman(user.getEmployee().getForeman().getId());
        } else {
            allTeams = teamService.findAllTeams();
        }
        List<Team> availableTeams = new LinkedList<Team>();
        for (Team team : allTeams) {
            if (team.getId() != DEFAULT_TEAM_ID) {
                availableTeams.add(team);
            }
        }
        return availableTeams;
    }
}
